package com.example;

import com.alibaba.fastjson.JSONObject;
import com.example.druid.DataSourceConfig;
import org.I0Itec.zkclient.ZkClient;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @author lbq
 * @version 1.0
 * @date 2021/11/24 21:46
 */
public class TestDemo {
    public static void main(String[] args) throws SQLException {

        DataSourceConfig.init();

        final ZkClient zkClient = new ZkClient("node2:2181");

        while (true) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入数字: ");
            final int i = scanner.nextInt();
            if (i % 3 == 0) {
                Map<String, String> map = new HashMap<>();
                map.put(DataSourceConfig.URL, "jdbc:mysql://node2:3306/lagou_study?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true");
                map.put(DataSourceConfig.CLASS_NAME, "com.mysql.jdbc.Driver");
                map.put(DataSourceConfig.USERNAME, "hive");
                map.put(DataSourceConfig.PASSWORD, "12345678");
                zkClient.writeData("/datasource", JSONObject.toJSONString(map));
            } else if (i % 3 == 1) {
                DataSource dataSource = DataSourceConfig.getDataSource();
                Connection connection = dataSource.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement("select * from r_user");
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    System.out.println("id : " + resultSet.getString(1));
                    System.out.println("email : " + resultSet.getString(2));
                    System.out.println("password : " + resultSet.getString(3));
                    System.out.println("register_time : " + resultSet.getString(4));
                }
                resultSet.close();
                preparedStatement.close();
                connection.close();
            } else {
                Map<String, String> map = new HashMap<>();
                map.put(DataSourceConfig.URL, "jdbc:mysql://127.0.0.1:3306/lagou_study?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true");
                map.put(DataSourceConfig.CLASS_NAME, "com.mysql.jdbc.Driver");
                map.put(DataSourceConfig.USERNAME, "root");
                map.put(DataSourceConfig.PASSWORD, "root");
                zkClient.writeData("/datasource", JSONObject.toJSONString(map));
            }
        }
    }
}
